﻿using UnityEngine;
using System.Collections;

public class PlatformCircleMovement : MonoBehaviour
{
	public bool isStationary;
	public float radius;
	public float rotationSpeed;
	public float axisSpeed;
	public float distance;
	public Vector3 offset;
	public string axisRotation;

	private float angle;
	private float start;
	private float end;
	private Transform PlatformTransform;
	private bool move;

	void Start()
	{
		move = true;
		PlatformTransform = transform;
		angle = 0;
		if(axisRotation == "x")
		{
			start = rigidbody.position.x;
			end = rigidbody.position.x + distance;
		}
		if(axisRotation == "y")
		{
			start = rigidbody.position.y;
			end = rigidbody.position.y + distance;
		}
		if(axisRotation == "z")
		{
			start = rigidbody.position.z;
			end = rigidbody.position.z + distance;
		}
	}
	
	void FixedUpdate()
	{
		if(axisRotation == "x")
			{
			float y = offset.y + Mathf.Sin(angle) * radius;
			float z = offset.z + Mathf.Cos(angle) * radius;
			PlatformTransform.position = new Vector3 (PlatformTransform.position.x, y, z);

			if(!isStationary)
			{
				if(move)
				{
					PlatformTransform.position += Vector3.right * axisSpeed;
					
					if(rigidbody.position.x >= end)
					{
						move = false;
					}
				}
				else 
				{
					PlatformTransform.position -= Vector3.right * axisSpeed;
					
					if(rigidbody.position.x <= start)
					{
						move = true;
					}
				}
			}

			angle += rotationSpeed;

			if(angle > 360)
			{
				angle = 0;
			}

			if(angle < 0)
			{
				angle = 360;
			}
		}
		if(axisRotation == "y")
		{
			float x = offset.x + Mathf.Sin(angle) * radius;
			float z = offset.z + Mathf.Cos(angle) * radius;
			PlatformTransform.position = new Vector3 (x, PlatformTransform.position.y, z);

			if(!isStationary)
			{
				if(move)
				{
					PlatformTransform.position += Vector3.up * axisSpeed;
					
					if(rigidbody.position.y >= end)
					{
						move = false;
					}
				}
				else 
				{
					PlatformTransform.position -= Vector3.up * axisSpeed;
					
					if(rigidbody.position.y <= start)
					{
						move = true;
					}
				}
			}
			
			angle += rotationSpeed;
			
			if(angle > 360)
			{
				angle = 0;
			}
			
			if(angle < 0)
			{
				angle = 360;
			}
		}
		if(axisRotation == "z")
		{
			float x = offset.x + Mathf.Sin(angle) * radius;
			float y = offset.y + Mathf.Cos(angle) * radius;
			PlatformTransform.position = new Vector3 (x, y, PlatformTransform.position.z);

			if(!isStationary)
			{
				if(move)
				{
					PlatformTransform.position += Vector3.forward * axisSpeed;
					
					if(rigidbody.position.z >= end)
					{
						move = false;
					}
				}
				else 
				{
					PlatformTransform.position -= Vector3.forward * axisSpeed;
					
					if(rigidbody.position.z <= start)
					{
						move = true;
					}
				}
			}
			
			angle += rotationSpeed;
			
			if(angle > 360)
			{
				angle = 0;
			}
			
			if(angle < 0)
			{
				angle = 360;
			}
		}
	}
}